using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 增强的章节内容生成服务
    /// 实现完整的正文生成流程：前章衔接+时间线+角色信息+细纲生成
    /// </summary>
    public class EnhancedChapterContentService
    {
        private readonly ILogger<EnhancedChapterContentService> _logger;
        private readonly IAIService _aiService;
        private readonly IDataStorageService _dataStorage;
        private readonly TimelineService _timelineService;
        private readonly ContentQualityService _contentQualityService;
        private readonly WorldSettingService _worldSettingService;

        public EnhancedChapterContentService(
            ILogger<EnhancedChapterContentService> logger,
            IAIService aiService,
            IDataStorageService dataStorage,
            TimelineService timelineService,
            ContentQualityService contentQualityService,
            WorldSettingService worldSettingService)
        {
            _logger = logger;
            _aiService = aiService;
            _dataStorage = dataStorage;
            _timelineService = timelineService;
            _contentQualityService = contentQualityService;
            _worldSettingService = worldSettingService;
        }

        /// <summary>
        /// 生成增强的章节内容
        /// </summary>
        public async Task<EnhancedChapterResult> GenerateEnhancedChapterContentAsync(
            EnhancedChapterRequest request,
            CancellationToken cancellationToken = default)
        {
            var result = new EnhancedChapterResult();
            var startTime = DateTime.Now;

            try
            {
                _logger.LogInformation($"开始生成增强章节内容: 第{request.ChapterNumber}章");

                // 1. 收集上下文信息
                var context = await CollectChapterContextAsync(request);
                cancellationToken.ThrowIfCancellationRequested();

                // 2. 生成章节正文
                var rawContent = await GenerateChapterContentWithContextAsync(request, context);
                cancellationToken.ThrowIfCancellationRequested();

                // 3. 清理内容（移除output标签等）
                var cleanedContent = _contentQualityService.CleanOutputTags(rawContent);
                
                // 4. 质量检查（简化版本）
                var qualityScore = CalculateSimpleQualityScore(cleanedContent);
                
                result.Content = cleanedContent;
                result.WordCount = CountChineseCharacters(cleanedContent);
                result.QualityScore = qualityScore;
                result.IsSuccess = true;
                result.GenerationTime = DateTime.Now - startTime;

                _logger.LogInformation($"增强章节内容生成完成: 第{request.ChapterNumber}章, 字数: {result.WordCount}");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成增强章节内容失败: 第{request.ChapterNumber}章");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                result.GenerationTime = DateTime.Now - startTime;
                return result;
            }
        }

        /// <summary>
        /// 收集章节上下文信息
        /// </summary>
        private async Task<EnhancedChapterContext> CollectChapterContextAsync(EnhancedChapterRequest request)
        {
            var context = new EnhancedChapterContext();

            try
            {
                // 1. 获取前一章节的最后一节内容
                if (request.ChapterNumber > 1)
                {
                    context.PreviousChapterEnding = await GetPreviousChapterEndingAsync(
                        request.ProjectId, request.ChapterNumber - 1);
                }

                // 2. 获取时间线的最后三章内容
                context.LastThreeChaptersTimeline = await _timelineService.GetLastThreeChaptersTimelineAsync(
                    request.ProjectId, request.ChapterNumber);

                // 3. 获取历史角色信息、角色关系和属性设定
                context.HistoricalCharacterInfo = await GetHistoricalCharacterInfoAsync(request.ProjectId);

                // 4. 获取本章出场的角色信息
                context.CurrentChapterCharacters = await GetCurrentChapterCharactersAsync(
                    request.ProjectId, request.ChapterOutline);

                // 5. 获取世界设定信息
                context.WorldSettings = await GetRelevantWorldSettingsAsync(
                    request.ProjectPath, request.ChapterNumber);

                _logger.LogInformation($"章节上下文收集完成: 第{request.ChapterNumber}章");
                return context;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"收集章节上下文失败: 第{request.ChapterNumber}章");
                throw;
            }
        }

        /// <summary>
        /// 获取前一章节的结尾内容
        /// </summary>
        private async Task<string> GetPreviousChapterEndingAsync(int projectId, int previousChapterNumber)
        {
            try
            {
                // 获取所有章节，然后找到指定章节号的章节
                var allChapters = await _dataStorage.GetChaptersAsync(projectId);
                var previousChapter = allChapters.FirstOrDefault(c => c.ChapterNumber == previousChapterNumber);

                if (previousChapter?.Content == null)
                {
                    return "";
                }

                // 获取最后800-1000字作为结尾内容
                var content = previousChapter.Content;
                var endingLength = Math.Min(1000, content.Length);
                var startIndex = Math.Max(0, content.Length - endingLength);

                var ending = content.Substring(startIndex);
                _logger.LogDebug($"获取到第{previousChapterNumber}章结尾内容: {ending.Length}字");

                return ending;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取第{previousChapterNumber}章结尾内容失败");
                return "";
            }
        }

        /// <summary>
        /// 获取历史角色信息
        /// </summary>
        private async Task<string> GetHistoricalCharacterInfoAsync(int projectId)
        {
            try
            {
                var characters = await _dataStorage.GetCharactersAsync(projectId);
                if (!characters.Any())
                {
                    return "";
                }

                var characterInfo = new List<string>();
                foreach (var character in characters)
                {
                    var info = $"**{character.Name}**\n";
                    info += $"- 描述：{character.Description}\n";
                    info += $"- 属性：{character.Attributes}\n";
                    info += $"- 类型：{character.Type}\n";
                    info += $"- 状态：{character.Status}\n";
                    characterInfo.Add(info);
                }

                var result = "=== 历史角色信息 ===\n" + string.Join("\n", characterInfo);
                _logger.LogDebug($"获取到历史角色信息: {characters.Count()}个角色");
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取历史角色信息失败");
                return "";
            }
        }

        /// <summary>
        /// 获取本章出场的角色信息
        /// </summary>
        private async Task<string> GetCurrentChapterCharactersAsync(int projectId, string chapterOutline)
        {
            try
            {
                // 从章节细纲中提取角色名称
                var characterNames = ExtractCharacterNamesFromOutline(chapterOutline);
                if (!characterNames.Any())
                {
                    return "";
                }

                var allCharacters = await _dataStorage.GetCharactersAsync(projectId);
                var currentChapterCharacters = allCharacters
                    .Where(c => characterNames.Any(name => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase)))
                    .ToList();

                if (!currentChapterCharacters.Any())
                {
                    return "";
                }

                var characterInfo = new List<string>();
                foreach (var character in currentChapterCharacters)
                {
                    var info = $"**{character.Name}**（本章出场）\n";
                    info += $"- 当前状态：{character.Description}\n";
                    info += $"- 能力属性：{character.Attributes}\n";
                    info += $"- 角色类型：{character.Type}\n";
                    info += $"- 重要程度：{character.Importance}\n";
                    characterInfo.Add(info);
                }

                var result = "=== 本章出场角色 ===\n" + string.Join("\n", characterInfo);
                _logger.LogDebug($"获取到本章出场角色信息: {currentChapterCharacters.Count}个角色");
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取本章出场角色信息失败");
                return "";
            }
        }

        /// <summary>
        /// 从章节细纲中提取角色名称
        /// </summary>
        private List<string> ExtractCharacterNamesFromOutline(string outline)
        {
            var names = new List<string>();
            
            try
            {
                // 使用正则表达式提取可能的角色名称
                // 这里可以根据实际情况调整正则表达式
                var patterns = new[]
                {
                    @"(?:主角|角色|人物)[：:]\s*([^\n]+)",
                    @"([^\s]+)(?:说道|说|道|想|心想|看到|发现)",
                    @"重要角色[：:]\s*([^\n]+)"
                };

                foreach (var pattern in patterns)
                {
                    var matches = Regex.Matches(outline, pattern, RegexOptions.IgnoreCase);
                    foreach (Match match in matches)
                    {
                        if (match.Groups.Count > 1)
                        {
                            var nameText = match.Groups[1].Value.Trim();
                            // 进一步处理提取的文本，分离出具体的角色名
                            var extractedNames = nameText.Split(new[] { '、', ',', '，', ' ' }, 
                                StringSplitOptions.RemoveEmptyEntries);
                            names.AddRange(extractedNames.Select(n => n.Trim()));
                        }
                    }
                }

                return names.Distinct().ToList();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "从章节细纲提取角色名称失败");
                return new List<string>();
            }
        }

        /// <summary>
        /// 获取相关的世界设定信息
        /// </summary>
        private async Task<string> GetRelevantWorldSettingsAsync(string projectPath, int chapterNumber)
        {
            try
            {
                // 这里可以调用WorldSettingService获取相关设定
                // 暂时返回空字符串，后续可以完善
                return "";
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取世界设定信息失败");
                return "";
            }
        }

        /// <summary>
        /// 使用上下文生成章节内容
        /// </summary>
        private async Task<string> GenerateChapterContentWithContextAsync(
            EnhancedChapterRequest request, EnhancedChapterContext context)
        {
            var prompt = BuildEnhancedChapterPrompt(request, context);
            
            // 使用较高的token限制以支持长文本生成
            var maxTokens = Math.Max(request.TargetWordCount * 2, 8000);
            
            return await _aiService.GenerateTextAsync(prompt, maxTokens, 0.9f);
        }

        /// <summary>
        /// 构建增强的章节生成提示词
        /// </summary>
        private string BuildEnhancedChapterPrompt(EnhancedChapterRequest request, EnhancedChapterContext context)
        {
            var prompt = $@"你是一位专业的小说作家，现在需要创作第{request.ChapterNumber}章的正文内容。

=== 创作要求 ===
- 目标字数：{request.TargetWordCount}字
- 严格按照章节细纲进行创作
- 确保与前文的自然衔接
- 保持角色行为的一致性
- 只输出标准小说正文，不要任何解释或标记

=== 章节细纲 ===
{request.ChapterOutline}

{(!string.IsNullOrEmpty(context.PreviousChapterEnding) ? $@"
=== 前一章结尾内容（必须自然衔接）===
{context.PreviousChapterEnding}
" : "")}

{(!string.IsNullOrEmpty(context.LastThreeChaptersTimeline) ? $@"
=== 最近三章时间线参考 ===
{context.LastThreeChaptersTimeline}
" : "")}

{(!string.IsNullOrEmpty(context.HistoricalCharacterInfo) ? $@"
{context.HistoricalCharacterInfo}
" : "")}

{(!string.IsNullOrEmpty(context.CurrentChapterCharacters) ? $@"
{context.CurrentChapterCharacters}
" : "")}

=== 创作指导 ===
1. 如果有前章结尾内容，必须与之自然衔接，不能突兀
2. 参考时间线信息，保持故事的连贯性和逻辑性
3. 严格按照角色设定来描写角色的行为、对话和心理
4. 本章出场的角色要特别注意其当前状态和能力属性
5. 情节发展要自然流畅，符合细纲设定
6. 对话要生动真实，符合角色性格
7. 描写要细腻丰富，包含环境、动作、心理等多层面描写
8. 保持适当的节奏感和张力
9. 只输出小说正文内容，不要包含任何<output>标签或其他标记

请开始创作第{request.ChapterNumber}章的正文：";

            return prompt;
        }

        /// <summary>
        /// 统计中文字符数
        /// </summary>
        private int CountChineseCharacters(string text)
        {
            if (string.IsNullOrEmpty(text))
                return 0;

            return text.Count(c => c >= 0x4e00 && c <= 0x9fff);
        }

        /// <summary>
        /// 计算简单的质量分数
        /// </summary>
        private float CalculateSimpleQualityScore(string content)
        {
            if (string.IsNullOrEmpty(content))
                return 0f;

            float score = 0.5f; // 基础分数

            // 根据长度调整分数
            var length = content.Length;
            if (length > 1000) score += 0.2f;
            if (length > 3000) score += 0.2f;

            // 检查是否包含对话
            if (content.Contains('"') || content.Contains('"') || content.Contains('"')) score += 0.1f;

            return Math.Min(1.0f, score);
        }
    }

    /// <summary>
    /// 增强章节生成请求
    /// </summary>
    public class EnhancedChapterRequest
    {
        public int ProjectId { get; set; }
        public string ProjectPath { get; set; } = "";
        public int ChapterNumber { get; set; }
        public string ChapterOutline { get; set; } = "";
        public int TargetWordCount { get; set; } = 6500;
        public string BookTitle { get; set; } = "";
        public string CreativeDirection { get; set; } = "";
    }

    /// <summary>
    /// 增强章节上下文
    /// </summary>
    public class EnhancedChapterContext
    {
        public string PreviousChapterEnding { get; set; } = "";
        public string LastThreeChaptersTimeline { get; set; } = "";
        public string HistoricalCharacterInfo { get; set; } = "";
        public string CurrentChapterCharacters { get; set; } = "";
        public string WorldSettings { get; set; } = "";
    }

    /// <summary>
    /// 增强章节生成结果
    /// </summary>
    public class EnhancedChapterResult
    {
        public bool IsSuccess { get; set; }
        public string Content { get; set; } = "";
        public int WordCount { get; set; }
        public float QualityScore { get; set; }
        public string ErrorMessage { get; set; } = "";
        public TimeSpan GenerationTime { get; set; }
        public List<string> Warnings { get; set; } = new();
        public List<string> Suggestions { get; set; } = new();
    }
}
